<template>
	<view class="uni-container">
		<uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind">
			<uni-forms-item name="name" label="名称">
				<uni-easyinput v-model="formData.name" />
			</uni-forms-item>
			<uni-forms-item name="src" label="封面图">
				<image v-if="formData.src" :src="formData.src" mode="aspectFill" class="suoluetu"></image>
				<text class='cuIcon-cameraadd text-sl' @click="upload"></text>
			</uni-forms-item>
			<uni-forms-item name="address" label="地址">
				<cloud-map @change="changeAddress"></cloud-map>
			</uni-forms-item>
			<uni-forms-item name="mobile" label="电话">
				<uni-easyinput placeholder="" v-model="formData.mobile" />
			</uni-forms-item>

			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import validator from '@/js_sdk/validator/cloud_self_raising_points.js';
	import {
		uploadFiles
	} from '@/common/js/util.js';
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'cloud_self_raising_points';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}

	export default {
		data() {
			return {
				formOptions: {},
				formData: {
					"address": "",
					"latitude": null,
					"longitude": null,
					"location": null,
					"mobile": "",
					"name": "",
					"src": ""
				},
				rules: {
					...getValidator(["address", "latitude", "longitude", "location", "mobile", "name", "src"])
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					console.log(res)
					this.submitForm(this.formData)
				}).catch((errors) => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				// 使用 uni-clientDB 提交数据
				db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			changeAddress(data){
				console.log(data)
				this.formData = Object.assign(this.formData,data);
			},
			upload() {
				uploadFiles("selfraising", 1, (src) => {
					this.formData.src = src[0]
				});
			}
		}
	}
</script>
